package dao

import (
	"admin-api/app/models/entity"
	"admin-api/app/models/response"
	"admin-api/core"
	"gitee.com/molonglove/goboot/gorm"
)

var Post = new(PostDao)

type PostDao struct{}

// VerifyNameOrCodeRepetition 验证岗位名称或编码是否重复
func (p *PostDao) VerifyNameOrCodeRepetition(name, code string) bool {
	var num int64
	builder := core.DB.Builder().
		Select(gorm.Count("post_id")).
		From("sys_post")
	if code != "" {
		builder.Where(gorm.Eq("post_code", code))
	}
	if name != "" {
		builder.Where(gorm.Eq("post_name", name))
	}
	if err := builder.QExecute(&num).Error; err != nil {
		core.Log.Error("验证岗位名称或编码是否重复错误: %s", err.Error())
		return true
	}
	if num > 0 {
		return true
	}
	return false
}

// Exist 条件查询岗位信息是否存在
func (p *PostDao) Exist(condition *gorm.DB) (bool, error) {
	var (
		total int64
		err   error
	)
	if err = condition.Model(&entity.Post{}).Count(&total).Error; err != nil {
		return false, err
	}
	if total > 0 {
		return true, nil
	}
	return false, nil
}

// Create 创建岗位
func (p *PostDao) Create(tx *gorm.DB, post *entity.Post) error {
	return tx.Create(post).Error
}

// UpdateById 更新菜单
func (p *PostDao) UpdateById(tx *gorm.DB, post *entity.Post) error {
	return tx.Save(post).Error
}

// Delete 删除数据
func (p *PostDao) Delete(tx *gorm.DB, postId ...int64) error {
	return tx.Where("post_id in ?", postId).Delete(&entity.Post{}).Error
}

// GetById 通过ID获取岗位数据
func (p *PostDao) GetById(postId int64) (post entity.Post, err error) {
	err = core.DB.Model(&entity.Post{}).
		Where("post_id = ?", postId).
		First(&post).
		Error
	return
}

// List 岗位列表
func (p *PostDao) List(condition *gorm.DB) (post []entity.Post, err error) {
	err = condition.Model(&entity.Post{}).Find(&post).Error
	return
}

// GetPostByUserId 获取岗位通过用户ID
func (p *PostDao) GetPostByUserId(userId int64) (posts []response.UserPostProp, err error) {
	err = core.DB.Namespace("post").
		DQuery("getPostByUserId", map[string]any{"UserId": userId}).
		TSelect(&posts).
		Error
	//err = core.DB.Model(entity.Post{}).
	//	Alias("sp").
	//	Where("exists(select 1 from sys_user_post sup where sup.user_id = ? and sup.post_id = sp.post_id)", userId).
	//	Find(&posts).
	//	Error
	return
}
